<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Role;
use Symfony\Component\HttpKernel\Exception\HttpException;

class RoleController extends Controller
{
    protected function initialize()
    {
        $this->model = new Role();
    }

    public function index(Request $request)
    {
        $page = $request->query('page', 1);
        $pageSize = $request->query('pageSize', 10);

        $name = $request->query('name');
        $code = $request->query('code');

        $model = $this->model;

        if ($name !== null) {
            $model = $model->where('name', 'like', "%{$name}%");
        }

        if ($code !== null) {
            $model = $model->where('code', 'like', "%{$code}%");
        }

        $model = $model->paginate(
            (int)$pageSize,
            ['*'],
            'page',
            (int)$page
        );

        return $this->successList(list: $model->items(), total: $model->total());
    }

    public function store(Request $request)
    {
        $body = $request->json()->all();

        $body['menuPermissions'] = json_encode($body['menuPermissions']);

        try {
            $this->model::create($body);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function show($id)
    {
        try {
            $model = $this->model->find($id)->toArray();

            $model['menuPermissions'] = json_decode($model['menuPermissions']);

            return $this->success(data: $model);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function update($id, Request $request)
    {
        $body = $request->json()->all();
        try {
            $this->model::where('id', $id)->update($body);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function destroy($id)
    {
        try {
            $this->model::destroy($id);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function batchDelete(Request $request)
    {
        $ids = $request->json('ids');
        try {
            $this->model::destroy($ids);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function all()
    {
        try {
            $model = $this->model->all();
            return $this->success(data: $model);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }
}
